﻿#include "TaskQuality.h"

TaskQuality::TaskQuality(QObject *parent) : MyObject(parent)
{

}

void TaskQuality::Start(){
    QThread::sleep(2);

    sqlBase = new SqlBase();
    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(OnTimer()));
    timer->start(1*1000);
}

void TaskQuality::Stop(){
    timer->stop();
    emit Finished();
}

void TaskQuality::OnTimer(){
    this->CheckQuality();
}

void TaskQuality::CheckQuality(){
    mutex.lock();

    for(int i = 0; i<globalData->simList.size(); i++){
        Simulation *equ = globalData->simList[i];

        if(!qualityMap.contains(equ->devname)){
            qualityMap.insert(equ->devname, new QStringList);
        }

        QStringList *list = qualityMap.value(equ->devname);
        QString line = QString("%1,%2")
                            .arg(QString::number(equ->launch, 'f', 1))
                            .arg(QString::number(equ->reflect, 'f', 1));
        list->append(line);

        //120秒保存一条数据
        if(list->size() >= 120){
            this->SaveQuality(equ->devname);
            list->clear();
        }
    }

    mutex.unlock();
}

void TaskQuality::SaveQuality(QString code){

    QStringList *list = qualityMap.value(code);

    if(!list || list->size() <= 0) return;

    Quality bean;
    bean.code = code;
    bean.endTime = QDateTime::currentDateTime();
    bean.startTime = bean.endTime.addSecs(-1 * list->size());
    bean.data = list->join("|");
    sqlBase->SaveQuality(bean);

    list->clear();
}
